#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
配置管理模块
"""

import os
import yaml
import logging
from pathlib import Path

# 默认配置
DEFAULT_CONFIG = {
    "app": {
        "name": "脚本调度UI",
        "version": "0.2.0",
        "data_dir": "./data",
        "log_dir": "./logs",
    },
    "database": {
        "type": "sqlite",
        "path": "./data/scheduler.db",
    },
    "cluster": {
        "enabled": False,
        "redis_url": "redis://localhost:6379/0",
        "nodes": [],
    },
    "triggers": {
        "file": {
            "enabled": True,
            "watch_dirs": [],
        },
        "webhook": {
            "enabled": True,
            "port": 8000,
            "endpoints": [],
        },
        "email": {
            "enabled": False,
            "check_interval": 300,  # 秒
            "accounts": [],
        },
        "schedule": {
            "enabled": True,
            "jobs": [],
        },
    },
}


def get_config_path():
    """获取配置文件路径"""
    # 首先检查当前目录
    config_path = Path("./config.yaml")
    if config_path.exists():
        return config_path
    
    # 检查用户目录
    user_config = Path.home() / ".fangYB" / "config.yaml"
    if user_config.exists():
        return user_config
    
    # 返回默认路径
    return config_path


def load_config():
    """加载配置文件"""
    config_path = get_config_path()
    config = DEFAULT_CONFIG.copy()
    
    try:
        if config_path.exists():
            with open(config_path, "r", encoding="utf-8") as f:
                user_config = yaml.safe_load(f)
                if user_config:
                    # 递归更新配置
                    _update_dict(config, user_config)
            logging.info(f"已加载配置文件: {config_path}")
        else:
            # 创建默认配置文件
            os.makedirs(config_path.parent, exist_ok=True)
            save_config(config)
            logging.info(f"已创建默认配置文件: {config_path}")
    except Exception as e:
        logging.error(f"加载配置文件失败: {e}")
    
    return config


def save_config(config):
    """保存配置到文件"""
    config_path = get_config_path()
    try:
        os.makedirs(config_path.parent, exist_ok=True)
        with open(config_path, "w", encoding="utf-8") as f:
            yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
        logging.info(f"配置已保存到: {config_path}")
        return True
    except Exception as e:
        logging.error(f"保存配置失败: {e}")
        return False


def _update_dict(d, u):
    """递归更新字典"""
    for k, v in u.items():
        if isinstance(v, dict) and k in d and isinstance(d[k], dict):
            _update_dict(d[k], v)
        else:
            d[k] = v
    return d